//
//  RecordSupplyFormController.swift
//  mggz
//
//  Created by ShareAnimation on 2017/8/21.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit

class RecordSupplyFormController: UIViewController {
    var signOutAlert2:TWLAlertView?
    var recordTrackModels = [RecordTrack]()
    var recordHistroyCommitModel: RecordCommitHistory?//历史提交记录，如果有的话
    fileprivate var _tableView: UITableView!
    fileprivate var selectPoint:String?
    fileprivate var supplyGuid:String?
    fileprivate var hourSelectPoint:String?
    fileprivate var tableView: UITableView {
        get {
            if _tableView != nil {
                return _tableView
            }
            _tableView = UITableView(frame: CGRect.zero, style: .grouped)
            _tableView.delegate = self
            _tableView.dataSource = self
            _tableView.rowHeight = UITableViewAutomaticDimension
            _tableView.estimatedRowHeight = 44
            //_tableView.setEditing(true, animated: true)
            _tableView.separatorStyle = .none
          //  _tableView.allowsSelectionDuringEditing = true
            
            _tableView.register(UITableViewCell.self, forCellReuseIdentifier: "\(UITableViewCell.self)")
            _tableView.register(RecordTimelineCell.self, forCellReuseIdentifier: "\(RecordTimelineCell.self)")
         _tableView.register(RecordSupply_RecordTimeCell.self, forCellReuseIdentifier: "\(RecordSupply_RecordTimeCell.self)")
            _tableView.register(TextViewCell.self, forCellReuseIdentifier: "\(TextViewCell.self)")
            _tableView.register(UINib.init(nibName: "WorkPointsSelectCell", bundle: nil), forCellReuseIdentifier: "workpoint")
            
            _tableView.register(UINib.init(nibName: "AnomalyTackCell", bundle: nil), forCellReuseIdentifier: "track")
            return _tableView
        }
    }
    
    var commitButton: UIButton = {
        let button = UIButton()
        button.backgroundColor = UIColor.mg_blue
        button.setTitle("提交", for: .normal)
        button.titleLabel?.font = wwFont_Medium(16)
        button.layer.cornerRadius = 10
        button.layer.shadowColor = UIColor.black.cgColor
        button.layer.shadowOpacity = 0.2
        button.layer.shadowOffset = CGSize(width: 1, height: 1)
        return button
    }()
    
    var sectionTitles = ["今日入场签到0次，出场签退0次，工时共计0个小时", "","", "缺工原因"]
    
    //必要的传入参数。表示当前项目
    var projectModel: ProjectModel?
    //比要的传入参数。此时这个页面的date
    var selectDate: Date?
    
    /***本地变量***/
    var recordItems:[RecordModel]?
    var unRecordReason: String = ""
   // var recordHistroyCommitModel: RecordCommitHistory?//历史提交记录，如果有的话
  //  var entryArray = [String]() //界面上签入section中的cell数，不包括最后一条
  //  var exitArray = [String]() ////界面上签出section中的cell数，不包括最后一条

    override func viewDidLoad() {
        super.viewDidLoad()
        self.getTrackData()
        selectPoint = "0.25"
        hourSelectPoint = "0.5"
        self.view.backgroundColor = UIColor.mg_backgroundGray
        self.getHistoryCommitData()
        self.getRecordData()
        self.view.addSubview(self.tableView)
        self.tableView.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.view).offset(80)
            make.bottom.equalTo(self.view).offset(-64)
        }
    }
    
    func getTrackData() {
        guard self.selectDate != nil else {
            return
        }
        let currentDateString = dateToString(date: self.selectDate!)
        let startOfDay = currentDateString + " " + "00:00:00"
        let endOfDay = currentDateString + " " + "23:59:59.998"
        if let marketSupplyBaseID = self.projectModel!.marketSupplyBaseID {
            RecordTrack.getRecordTrack(marketSupplyBaseID: marketSupplyBaseID,start: 0, startOfDay: startOfDay, endOfDay: endOfDay){(response) in
                if response.success {
                    self.recordTrackModels = response.value!
                    self.tableView.reloadData()
                }
                else {
                    WWError(response.message)
                }
            }
        }
    }
    
    
    
    
    
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        WWProgressHUD.dismiss()
    }
    @objc func doCommitAction() {
        var alertStr:String?
        alertStr = "你确认提交吗,"
        guard ((self.projectModel?.workDayType) != nil) else {
            return
        }
        if self.projectModel?.workDayType == 2 {

            self.selectPoint = "0"
            alertStr = "是否确认提交补" + self.hourSelectPoint! + "小时,"
        }else{

            self.hourSelectPoint = "0"
            alertStr = "是否确认提交补" + self.selectPoint! + "工,"
        }
        guard let model = self.projectModel, let businessChangerID = model.businessChangerID else {
            WWError("当前项目是空的")
            return
        }
        guard let demandBaseMigrantWorkerId = model.demandBaseMigrantWorkerID else {
            WWError("当前demandBaseMigrantWorkerId是空的")
            return
        }
        guard let signedDate = self.selectDate else{
            WWError("补工日期错误")
            return
        }
        guard self.unRecordReason.count > 0 else {
            WWError("缺工原因是空的！")
            return
        }
//        guard self.entryArray.count != 0 || self.exitArray.count != 0 else {
//            WWError("没有添加任何记录")
//            return
//        }
        let sureStr = alertStr! + " 一旦提交将不能撤回!"
        let alertController = ETSimpleAlertController.init(sureStr) {[unowned self] in
            
            let dateString = dateToString(date: signedDate)
           // let guidCount = 1 + self.entryArray.count +  self.exitArray.count
          //  var guidList: [String]?
            var orderNo: String?
            
            let dispatchGroup = DispatchGroup()
        
            dispatchGroup.enter()//组1
            UserModel.getGuid { (response) in
                if response.success{
                    self.supplyGuid = response.value
                }
                else {
                    
                }
                dispatchGroup.leave()
            }
            dispatchGroup.enter()//组2
            let orderConfigId = "6c2eff7d-fbb8-b727-ae1c-04fcdb47aabe"//这是补签申请表单固定的
            UserModel.getOrderNo(orderConfigId: orderConfigId) { (response) in
                if response.success {
                    orderNo = response.value //获取的表单编号
                }
                else {
                    WWError(response.message)
                }
                dispatchGroup.leave()
            }
            
            dispatchGroup.notify(queue: DispatchQueue.main) {
                guard orderNo != nil else {
                    return
                }
                guard (self.supplyGuid != nil) else{
                    return
                }
                
                //最后一个guid，即第guidCount个guid用来配置最外层的guid
                RecordSupply.applyForRecordSupply(guid: self.supplyGuid!, businessChangerId: businessChangerID, demandBaseMigrantWorkerID: demandBaseMigrantWorkerId, signedDate: dateString, orderNo: orderNo!, supplementReason: self.unRecordReason,orderConfigId: orderConfigId,supplyPoints:self.selectPoint!, hourPoints: self.hourSelectPoint!, workType: (self.projectModel?.workDayType)!) {(response) in
                    if response.success {
                        WWSuccess("提交成功")
               self.navigationController?.popViewController(animated: true)
                        
                    }
                    else {
                        WWError(response.message)
                    }
                    
                }
                
            }
        }
        self.present(alertController, animated: true, completion: nil)
    }
    
    //signedType：0表示签入, signedTime格式『yyyy-MM-dd HH:mm:ss』
    fileprivate func buQianMingXi(_ guid: String, signedType: Int, signedTime: String) -> [String: Any] {
        let dic = ["ID": guid, "SignedType": signedType, "SignedTime": signedTime, "Operate": 1] as [String : Any]
        return dic
    }
    //获取指定日期的签入签出统计
    func getRecordData() {
        let dateString = dateToString(date: self.selectDate!)
        
        //获取指定日期的签到记录
        if let model = self.projectModel {
            RecordModel.getRecordData(demandBaseMigrantWorkerID: model.demandBaseMigrantWorkerID!, signedDate: dateString, completionHandler: { (response) in
                if response.success {
                    self.recordItems = response.value
                    self.tableView.reloadSections(IndexSet.init(integer: 0), with: .automatic)
                }
                else {
                    
                    WWError(response.message)
                }
            })
        }
        
        
        //获取指定日期的签到统计,用于显示在section 0的头部
        RecordCountInOneDayModel.getRecordAcount(marketSupplyBaseId: self.projectModel!.marketSupplyBaseID!, signedDate: dateString) {(response) in
            if response.success {
                self.updateAcountData(entities: response.value!)
            }
            else {
                WWError(response.message)
            }
        }
    }
    
    //如果有历史补签，则获取历史补签记录并加载
    func getHistoryCommitData() {
        
        if let model = self.projectModel,let demandBaseMigrantWorkerID = model.demandBaseMigrantWorkerID {
            if selectDate != nil {
                let signedData = dateToString(date: self.selectDate!)
                
                WWBeginLoading()
                RecordCommitHistory.getRecordCommitHistory(demandBaseMigrantWorkerID, signedDate: signedData, completionHandler: { (response) in
                    WWEndLoading()
                    if response.success {
                        self.recordHistroyCommitModel = response.value
                        
                        if response.value != nil {
                            self.bindHistroyCommit(response.value!)
                        }
                        
                    }
                    else {
//                        WWError(response.message)
                    }
                })
            }
            else {
                WWError("当前日期错误，请退出后重新选择")
            }

        }
        else {
        }
        
    }
    
    //绑定历史提交记录，如果有的话
    fileprivate func bindHistroyCommit(_ model: RecordCommitHistory) {
        
        guard model.workflowState != nil else{
            return
        }
        switch model.workflowState! {
        case .approvalPending, .inTheFlow:
            self.commitButton.setTitle("正在审核中...", for: .normal)
            self.commitButton.backgroundColor = UIColor.mg_noDataGray
            self.commitButton.isEnabled = false
            let historyCell = self.tableView.cellForRow(at: IndexPath.init(row: 0, section: 2)) as! WorkPointsSelectCell
            historyCell.pointsSelect.isHidden = true
            if self.projectModel?.workDayType == 2{
                if (model.WorkHours != nil) {
                    self.hourSelectPoint = String(model.WorkHours!)
                }
            }else{
                if (model.WorkDays != nil) {
                    self.selectPoint = String(model.WorkDays!)
                }
            }
            let textViewCell = self.tableView.cellForRow(at: IndexPath.init(row: 0, section: 3)) as! TextViewCell
            textViewCell.detailTextView.text = model.supplementReason
            textViewCell.detailTextView.isEditable = false
            self.unRecordReason = model.supplementReason ?? ""
        default:
            let historyCell = self.tableView.cellForRow(at: IndexPath.init(row: 0, section: 2)) as! WorkPointsSelectCell
            historyCell.pointsSelect.isHidden = false
            let textViewCell = self.tableView.cellForRow(at: IndexPath.init(row: 0, section: 3)) as! TextViewCell
            textViewCell.detailTextView.isEditable = true
            self.commitButton.setTitle("提交", for: .normal)
            self.commitButton.isEnabled = true
            self.commitButton.backgroundColor = UIColor.mg_blue
        }
        self.tableView.reloadData()
    }
    
    //更新section one 头的统计信息
    fileprivate  func updateAcountData( entities:[RecordCountInOneDayModel]) {
        var signedIn = 0
        var signedOut = 0
        var workHours: String?
        for model in entities {
            if let signIncount = model.signedInCount {
                signedIn += Int(signIncount) ?? 0
            }
            if let signOutCount = model.signedOutCount {
                signedOut += Int(signOutCount) ?? 0
            }
            workHours = model.workingHours
        }
        
        var workHourFloat: Float = 0
        if workHours != nil {
            workHourFloat =  Float(workHours!)!
        }
        
        let workHourString = String.init(format: "%.2f", workHourFloat)
        let sectionOneTitle = "今日入场签到\(signedIn)次，出场签退\(signedOut)次，工时共计\(workHourString)小时"
        
        self.sectionTitles[0] = sectionOneTitle
        self.tableView.reloadSections(IndexSet.init(integer: 0), with: .automatic)
    }
}
extension RecordSupplyFormController: UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 3 {
            return 100
        }
        return 45
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return sectionTitles.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            if let items = self.recordItems {
                return items.count
            }
        }
        if section == 1 || section == 2 || section == 3{
            return  1
        }
        return 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {//签到记录时间
            let cell = tableView.dequeueReusableCell(withIdentifier: "\(RecordTimelineCell.self)", for: indexPath) as! RecordTimelineCell
            cell.backgroundColor = UIColor.white
            cell.bind(self.recordItems![indexPath.row])
            if indexPath.row == 0 {
                cell.hideTopLine = true
            }
            if let items = self.recordItems {
                if indexPath.row == items.count - 1 && indexPath.row >= 0 {
                    cell.hideBottomLine = true
                }
            }
            return cell
        }
        if  indexPath.section == 2  {
            let cell : WorkPointsSelectCell = tableView.dequeueReusableCell(withIdentifier: "workpoint") as! WorkPointsSelectCell
            cell.pointsSelect.addTarget(self, action: #selector(pointsSelectClick), for: .touchUpInside)
            
            if self.projectModel?.workDayType == 2{
                cell.workPoints.text = hourSelectPoint
                 cell.postLabel.text = "小时"
            }else{
                cell.workPoints.text = selectPoint
                cell.postLabel.text = "工"
            }
            
            return cell
        }
        
        if indexPath.section == 1{
          let cell : AnomalyTackCell = tableView.dequeueReusableCell(withIdentifier: "track") as! AnomalyTackCell
        cell.setCellDataWith(self.recordTrackModels.count)
           return cell
        }
        if indexPath.section == 3 {//缺签原因
            let cell = tableView.dequeueReusableCell(withIdentifier: "\(TextViewCell.self)", for: indexPath) as! TextViewCell
            cell.textViewDidChange = {(text) in
                self.unRecordReason = text
            }
            return cell
        }
        let cell = tableView.dequeueReusableCell(withIdentifier: "\(UITableViewCell.self)", for: indexPath)
        return cell
    }
    @objc fileprivate func pointsSelectClick(){
        self.setupSignOutWorkPointsAlert()
    }
    fileprivate func setupSignOutWorkPointsAlert(){
        self.signOutAlert2 = TWLAlertView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
        let custom : RecordWorkpointsView2 = RecordWorkpointsView2.init(frame: CGRect(x: 0, y: 0, width: 240, height: 285))
        custom.cancelButton.addTarget(self, action: #selector(customCancelClick), for: .touchUpInside)
        custom.workType = self.projectModel?.workDayType
        custom.selectedPoints = {(value) in
            if self.projectModel?.workDayType == 2{
                
                self.hourSelectPoint = value
                
            }else{
                
            self.selectPoint = value
                
            }
        }
        custom.recordPoints.setTitle("确定", for: UIControlState.normal)
        custom.recordPoints.addTarget(self, action: #selector(recordPointsClick), for: .touchUpInside)
        self.signOutAlert2?.initWithCustomView(custom, frame: CGRect(x: 0, y: 0, width: 240, height: 285))
        let keyWindow = UIApplication.shared.keyWindow
        keyWindow?.addSubview(self.signOutAlert2!)
    }
    @objc fileprivate func recordPointsClick(){
        self.signOutAlert2?.cancleView()
        self.tableView.reloadData()
    }
    @objc fileprivate func customCancelClick(){
        self.signOutAlert2?.cancleView()
        self.selectPoint = "0.25"
        self.hourSelectPoint = "0.5"
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 1{
         let vc2 = RecordPathAbnormalController()
            vc2.title = "轨迹异常"
            vc2.currentDate = self.selectDate
            vc2.projectModel = self.projectModel
         self.navigationController?.pushViewController(vc2, animated: true)
            
        }else{
        tableView.deselectRow(at: indexPath, animated: true)
        }
    }
    //header
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        
        let label = UILabel()
        label.font = wwFont_Medium(13)
        view.addSubview(label)
        label.snp.makeConstraints { (make) in
            make.left.equalTo(view).offset(10)
            make.top.bottom.right.equalTo(view)
        }
        label.text = self.sectionTitles[section]
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1 || section == 2 {
            return 1
        }
        return 40
    }
    
    //footer
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if section == self.sectionTitles.count - 1 {
            let view = UIView()
            self.commitButton.addTarget(self, action: #selector(doCommitAction), for: .touchUpInside)
            view.addSubview(self.commitButton)
            self.commitButton.snp.makeConstraints({ (make) in
                
                make.center.equalTo(view)
                make.width.equalTo(180)
                make.height.equalTo(40)
                
            })
            return view
        }
        return nil
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == self.sectionTitles.count - 1 {
            return 80
        }
        return 0
    }
}
